package com.mhy.utils.toast;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.StringRes;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import com.mhy.utils.R;


/**
 * Created By Mahongyin
 * Date    2020/11/18 13:51
 * 使用WindowsManager添加view 显示toast
 */
public class WToast implements LifecycleObserver {
    public static final int LENGTH_SHORT = 2000;
    public static final int LENGTH_LONG = 3500;

    private final Handler mHandler = new Handler(Looper.myLooper() == null ? Looper.getMainLooper() : Looper.myLooper());
    private int mDuration = LENGTH_SHORT;
    private int mGravity = Gravity.CENTER;
    private int xO = 0, yO = 0;
    private View mView;//操作使用
    private View mNextView;//接收使用
    private WToast result;
    private WindowManager mWM;
    private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();

    private WToast(Context context) {
        mParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        mParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		//   wmParams!!.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
         //           WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR or
         //           WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
//        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;//添加这个是解决，焦点，点击的问题 ，仅外部可点击
        mParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;/*只要该窗口对用户可见，请保持*设备的屏幕处于打开状态且明亮不影响交互*/
        mParams.format = PixelFormat.TRANSLUCENT;//TRANSLUCENT半透明 //TRANSPARENT透明
        mParams.windowAnimations = android.R.style.Animation_Toast;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            mParams.packageName = context.getOpPackageName();
        } else {
            mParams.packageName = context.getPackageName();
        }

//         判断是否为 Android 6.0 及以上系统并且有悬浮窗权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(context)) {
            // 解决使用 WindowManager 创建的 Toast 只能显示在当前 Activity 的问题
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                mParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
        }else {
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mParams.type = WindowManager.LayoutParams.TYPE_PHONE;
//            mParams.type = WindowManager.LayoutParams.TYPE_TOAST;//对于非系统应用已弃用？不显示
        } else {
            mParams.type = WindowManager.LayoutParams.TYPE_APPLICATION;//没权限
        }
//        mParams.type = WindowManager.LayoutParams.TYPE_APPLICATION; //只显示在activity上
        mWM = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		}
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void pauseToast() {
        hide();
    }

    //外部创建Toast 唯一入口
    public static WToast makeText(Context context, CharSequence text, int duration) {
//        if (BuildConfig.DEBUG) {
//            if (!(context instanceof Activity)) {
//                throw new RuntimeException("The type context must be Activity");
//            }
//        }
        WToast result;
        Context ctx = context.getApplicationContext();
        if (ctx==null){
            ctx=context;
        }
        // 判断是否为 Android 6.0 及以上系统并且有悬浮窗权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(context)) {
//            有悬浮权限 全局显示
            result = new WToast(ctx);
        } else {
            result = new WToast(context);
            if (context instanceof LifecycleOwner) {
                ((LifecycleOwner) context).getLifecycle().addObserver(result);
            }
        }
//        result = new WToast(context);
//        if (context instanceof LifecycleOwner) {
//            ((LifecycleOwner) context).getLifecycle().addObserver(result);
//        }
        result.setText(context,text);
//        result.mNextView = view;
        result.mDuration = duration;
        return result;
    }

    private static void openFloat(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    /**
     * 设置view。{@link #setText} 两个方法不能同时调用
     */
    public void setView(View view) {
        mNextView = view;
    }

    /**
     * 返回view.
     */
    public View getView() {
        return mNextView;
    }

    /**
     * 此方法设置了默认样式 view   设置显示内容
     *
     * @param msg 显示内容
     *            {@link #setView} 两个方法不能同时调用
     */
    private void setText(Context context,CharSequence msg) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_toast, null);
        TextView mTextView = (TextView) view.findViewById(R.id.toast_message);
        mTextView.setText(msg);
        //不要焦点 不带点击
        view.setFocusable(false);
        view.setClickable(false);
        view.setFocusableInTouchMode(false);
        setView(view);
    }

    private void setText(Context context,@StringRes int strRes) {
        String msg = context.getResources().getString(strRes);
        setText(context,msg);
    }


    /**
     * 设置显示视图的时间.
     *
     * @see #LENGTH_SHORT
     * @see #LENGTH_LONG
     */
    public void setDuration(int duration) {
        mDuration = duration;
    }

    /**
     * 返回持续时间.
     *
     * @see #setDuration
     */
    public int getDuration() {
        return mDuration;
    }

    /**
     * 设置视图的边距。
     *
     * @param horizontalMargin 容器边缘和通知之间的水平边距，以容器宽度的百分比表示
     * @param verticalMargin   容器边缘和通知之间的垂直边距，以容器高度的百分比表示
     */
    public void setMargin(float horizontalMargin, float verticalMargin) {
        mParams.verticalMargin = verticalMargin;
        mParams.horizontalMargin = horizontalMargin;
    }

    /**
     * 设置通知应在屏幕上出现的位置.
     *
     * @see Gravity
     */
    public void setGravity(int gravity, int xOffset, int yOffset) {
        mGravity = gravity;
        xO = xOffset;
        yO = yOffset;
    }


    /**
     * 执行Show  延时自动hide
     */
    public void show() {
        mHandler.post(mShow);

        if (mDuration > 0) {
            mHandler.postDelayed(mHide, mDuration);
        }
    }

    /**
     * 执行Hide
     */
    public void hide() {
        mHandler.removeCallbacks(mHide);//先移除定时关闭的
        mHandler.post(mHide);//主动关闭
    }

    private final Runnable mShow = new Runnable() {
        public void run() {
            handleShow();
        }
    };

    private final Runnable mHide = new Runnable() {
        public void run() {
            handleHide();
        }
    };


    private void handleShow() {
        if (mView != mNextView) {
            //如有必要，删除旧视图
            handleHide();//remove上一view
            mView = mNextView;
            //位置
            mParams.gravity = mGravity;
            mParams.x = xO;
            mParams.y = yO;
            if ((mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {
                mParams.horizontalWeight = 1.0f;
            }
            if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {
                mParams.verticalWeight = 1.0f;
            }
//            mParams.verticalMargin = mVerticalMargin; //与容器边距
//            mParams.horizontalMargin = mHorizontalMargin;
            if (mView.getParent() != null) {
                mWM.removeView(mView);
            }
            mWM.addView(mView, mParams);
        }
    }

    private void handleHide() {
        if (mView != null) {
            if (mView.getParent() != null) {
                mWM.removeView(mView);
                mHandler.removeCallbacks(mHide);
            }
            mView = null;
        }
    }
}
